<template>
  <div class="app-container">
    <u-page-config
      :filter-array="filterArray"
      labelWidth="60px"
      v-model="filter"
      :actionBtn="actionBtn"
      label-width="100px"
      :getList="getList"
      :tableData="tableData"
      :tableColumn="tableColumn"
      :total="total"
      :loading="loading"
      showSelection
      @handleSelectionChange="handleSelectionChange"
      @addRow="addRow"
      @removeRow="removeRow"
      @editRow="editRow"
      @rowDetail="rowDetail"
      @export="handleExport"
    >
      <template #filteBranchCode="scope">
        <treeselect
          style="width:240px"
          v-model="filter.data.branchCode"
          :options="branchDataOptions"
          :normalizer="branchNormalizer"
          :show-count="true"
          placeholder="选择网点"
          noOptionsText="暂无选项"
          noResultsText="没有匹配的搜索结果"
        />
      </template>
    </u-page-config>

    <el-dialog :title="title" :visible.sync="visible" width="900px" :close-on-click-modal="false">
      <u-form ref="uFormRef" label-width='134px' v-model="form" :defaultForm="defaultForm" :formArray="formArray"
              :detailArray="detailArray" :show-btn="false" @submit="onsubmit" @close="visible = false" :mode="mode">
        <template #branchCode="scope">
          <!-- 1 -->
          <treeselect style="width:100%" v-model="form.branchCode" :options="branchDataOptions"
                      :normalizer="branchNormalizer" :show-count="true" placeholder="选择网点" noOptionsText="暂无选项"
                      noResultsText="没有匹配的搜索结果"/>
        </template>


        <template #image="scope">
          <u-file-upload :value="form.pic" :limit="3" :fileSize="10" @input="imageUploadChange"/>
        </template>
      </u-form>
    </el-dialog>
  </div>
</template>

<script>
import UPageConfig from '@/components/uPageConfig/index'
import UForm from '@/components/uForm'
import table from "@/mixin/uTable";
import Treeselect from "@riophae/vue-treeselect";

import {
  listDdmp,
  addDdmp,
  updateDdmp,
  delDdmp,
  getDdmp
} from '@/api/info/ddmp'
import {listManager} from "@/api/device/placeManager";

// import FillFormDialog from "@/views/device/adapterManagement/components/fillFormDialog";

export default {
  name: "UpdatePlan",
  mixins: [table],
  components: {UPageConfig, UForm, Treeselect},
  data() {
    return {
      filterArray: [
        {label: "标题", key: "title", type: "input"},
        { label: "网点", key: "branchCode", type: "slot", slot: 'filteBranchCode' }
      ],
      tableColumn: [
        {label: "标题", prop: "title"},
        // { label: "描述", prop: "description",type: 'slot', slot: "description", },
        {label: "照片", prop: "pic", type: 'image'},
        { label: "网点", prop: "branchCode",type: 'select', options: [],
          attr: {value: 'branchCode', label: 'branchName'}
        },
        {
          label: "操作", type: "btn", attr: {width: 180}, btnArr: [
            {
              icon: "el-icon-edit-outline",
              text: "修改",
              emit: "editRow",
              permissions: 'info:ddmp:edit'
            },
            {
              icon: "el-icon-delete",
              text: "删除",
              emit: "removeRow",
              permissions: 'info:ddmp:remove'
            },
          ]
        }
      ],
      actionBtn: [
        {
          type: 'primary',
          text: '创建',
          icon: 'el-icon-plus',
          emit: 'addRow',
          permissions: 'info:ddmp:add'
        },
        {
          type: 'success',
          text: '修改',
          icon: 'el-icon-edit',
          emit: 'editRow',
          permissions: 'info:ddmp:edit',
          disabledRule: () => this.ids.length !== 1
        },
        {
          type: 'danger',
          text: '删除',
          icon: 'el-icon-delete',
          emit: 'removeRow',
          permissions: 'info:ddmp:remove',
          disabledRule: () => this.ids.length === 0
        },
        {
          type: 'warning',
          text: '导出',
          icon: 'el-icon-download',
          emit: 'export',
          permissions: 'info:ddmp:export'
        },
      ],
      // 表单默认必填参数 重置表单时需要用到
      defaultForm: {
        description: '',
        title: '',
        pic: ''
      },
      formArray: [
        {
          label: "标题：", key: "title", col: 24, type: "input",
          rule: {required: true, message: '标题不能为空！', trigger: 'blur'},
        },
        {
          label: "网点: ", key: "branchCode", col: 24, type: "slot", slot: 'branchCode',
          rule: {required: true, message: '网点不能为空！', trigger: 'blur'},
        },
        {
          label: "描述：", key: "description", col: 24, type: "editor",
          rule: {required: true, message: '描述不能为空！', trigger: 'blur'},
        },
        {label: "照片：", key: "pic", col: 24, slot: "image"},

      ],
      // 查看详情表单配置
      detailArray: [
        {
          label: "标题：", key: "title", col: 24, type: "text",
        },
        {
          label: "描述：", key: "description", col: 24, type: "editor",
        },
        {label: "照片：", key: "pic", col: 24, type: "img"},
      ],
    };
  },
  computed: {
    // 网点树形数据
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || []
    },
  },
  methods: {
    /** 转换分组树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined,
      };
    },
    // 表单提交接口相关配置
    formSubmitFunConfig() {
      return {
        addFunc: addDdmp,
        modifyFunc: updateDdmp,
        pk: 'id',
        options: {
          ...this.form,
        },
        cbFunc: () => {
          this.visible = false
        }
      }
    },
    // 删除
    removeRow(row) {
      const id = row ? row.id : this.ids;
      this.removeTip(async () => {
        await delDdmp(id)
      }, row && row.id ? '该项数据' : '已勾选项数据')
    },
    // 添加
    addRow(row) {
      this.mode = 'form';
      this.title = "添加名片";
      this.visible = true;
    },
    // 修改
    async editRow(row) {
      this.mode = 'form'
      this.title = "修改名片";
      if (row) { //点击的表格内修改按钮
        this.form = JSON.parse(JSON.stringify(row))
      } else { //点击表格上方修改按钮
        const selectedItem = this.tableData.find(item => this.ids[0] === item.id) || {}
        this.form = JSON.parse(JSON.stringify(selectedItem))
      }
      this.visible = true
      await this.$nextTick()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    // 添加文件上传成功、删除图片时都会被调用
    imageUploadChange(imgUrl) {
      this.form.pic = imgUrl
    },
    /** 查询工单列表 */
    getList() {
      this.getInit(listDdmp, {})
    },
    /** 详细按钮操作 */
    rowDetail(row) {
      this.mode = 'text'
      // 直接拿到这一行的数据赋值
      this.form = row;
      this.visible = true
      this.title = '详细信息'
      // 如果当前行数据不完整 调接口拿详情数据
      this.getDetail('详细信息', getDdmp, row.id)
    },
    /** 返回设备部署页面 */
    goBack() {
      this.$router.go(-1);
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      const ids = this.ids;
      const params = this.getListRequestParams();
      this.download(
        "/info/ddmp/export",
        params,
        `名片列表_${currentDate}.xlsx`,
      );
    },
  },
  watch:{
    branchDataOptions: {
      handler(value){
        try {
          this.tableColumn.find(item => item.prop === 'branchCode').options = value;
        } catch (e) {
          console.log("找不到对应表单项", e)
        }
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
.form-item-wrap {
  display: flex;
}
</style>
